package hust.ning.jdo;

import hust.ning.ChatApp;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.mortbay.log.Log;

public class DAO {
	private static final Logger log = Logger.getLogger(ChatApp.class.getName());

	public static void saveChat(String uid, String content) {
		ChatItem ci = new ChatItem(uid, content, new Date());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(ci);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static int getUserCount() {
		try {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			String query = "select from " + UserCountItem.class.getName();
			List<UserCountItem> items = (List<UserCountItem>) pm
					.newQuery(query).execute();
			if (items.size() == 0) {
				UserCountItem uc = new UserCountItem();
				uc.setCount(1024);
				try {
					pm.makePersistent(uc);
				} finally {
					pm.close();
				}
				return 1024;
			}
			log.info("ning:getCount:" + items.get(0).getCount());
			return items.get(0).getCount();
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	@SuppressWarnings("unchecked")
	public static void incUserCount() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + UserCountItem.class.getName();
			List<UserCountItem> items = (List<UserCountItem>) pm
					.newQuery(query).execute();
			items.get(0).incCount();
			pm.makePersistent(items.get(0));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		// getUserCount();
	}

	public static List<ChatItem> getChatHistory() {
		return getChatHistory(0, Integer.MAX_VALUE);
	}

	public static List<ChatItem> getChatHistory(Date start) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(ChatItem.class, "date > start");// +
		query.declareImports("import java.util.Date");
		query.declareParameters("java.util.Date start");
		// query.declareParameters("java.util.Date end");
		query.setOrdering("date asc");
		query.setRange(0, 512);
		List<ChatItem> chats = (List<ChatItem>) pm.newQuery(query).execute(
				start);
		return chats;
	}

	public static List<ChatItem> getChatHistory(int start, int end) {
		try {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + ChatItem.class.getName()
		+"where id < " +
				end +
				" && id >" +
				start +
				""
				+ " order by date asc " ;
		List<ChatItem> chats = (List<ChatItem>) pm.newQuery(query).execute();
		return chats;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
